package com.silence.springboot.service.impl;


import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.silence.springboot.dto.UserRoleJoinRoleDto;
import com.silence.springboot.convert.RoleConvert;
import com.silence.springboot.dao.RoleDao;
import com.silence.springboot.dao.UserRoleDao;
import com.silence.springboot.entity.RoleEntity;
import com.silence.springboot.entity.UserRoleEntity;
import com.silence.springboot.enums.ResultCode;
import com.silence.springboot.exception.ApiException;
import com.silence.springboot.mapper.UserRoleMapper;
import com.silence.springboot.service.UserRoleService;
import com.silence.springboot.vo.input.SetRolesInput;
import com.silence.springboot.vo.output.AssignRolesOutput;
import com.silence.springboot.vo.output.RoleOutput;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;

/**
 * 用户角色关联表 服务层实现。
 *
 * @author mybatis-flex-helper automatic generation
 * @since 1.0
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRoleEntity> implements UserRoleService {

    /**
     * 用户角色关联表 数据访问对象。
     */
    private final UserRoleDao userRoleDao;

    /**
     * 权限表 数据访问对象。
     */
    private final RoleDao roleDao;

    /**
     * 权限表 转换类。
     */
    private final RoleConvert roleConvert;

    /**
     * 分配角色
     *
     * @param userId 用户id
     * @return 分配角色
     */
    @Override
    public AssignRolesOutput assignRoles(Long userId) {
        // 查询用户角色关联表
        List<UserRoleJoinRoleDto> userRoleList = userRoleDao.selectUserRoleJoinRole(List.of(userId));
        // 查询权限表
        List<RoleEntity> roleList = roleDao.selectAllRole();
        // 返回分配角色
        List<RoleOutput> roleOutputList = roleConvert.toRoleOutputList(roleList);
        return new AssignRolesOutput()
                .setUserRoleList(CollectionUtils.isEmpty(userRoleList) ? Collections.emptyList() : userRoleList)
                .setRoleList(CollectionUtils.isEmpty(roleOutputList) ? Collections.emptyList() : roleOutputList);
    }

    /**
     * 设置角色
     *
     * @param input 分配角色
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void setRoles(SetRolesInput input) {
        long userId;
        List<Long> roleIds;
        try {
            userId = Long.parseLong(input.getUserId());
            roleIds = input.getRoleIds().stream().map(Long::parseLong).toList();
        } catch (Exception e) {
            log.error("设置角色失败", e);
            throw new ApiException(ResultCode.PARAMS_PARSE_ERROR);
        }
        // 删除用户角色关联表
        userRoleDao.deleteUserRoleByUserId(userId);
        // 新增用户角色关联表
        roleIds.stream().map(roleId -> new UserRoleEntity().setUserId(userId).setRoleId(roleId))
                .forEach(this::save);
    }
}